<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author YDZ
-->
<template>
  <BasicDrawer v-bind="$attrs" :showFooter="true" :okAuth="'srm:asn:vouch:asnH:edit'" @register="registerDrawer"
    @ok="handleSubmit" width="80%">
    <template #title>
      <Icon :icon="getTitle.icon" class="m-1 pr-1" />
      <span> {{ getTitle.value }} </span>

      【<DictLabel :dictType="'xy_asn_dj_status'" :dictValue="record.djStatus" :defaultValue="0" />  】 
    </template>
    <BasicForm @register="registerForm">
      <template #asnCList>
        <!-- <a-button class="mt-2" @click="handleAsnCAdd" v-auth="'srm:asn:vouch:asnH:edit'">
          <Icon icon="i-ant-design:plus-circle-outlined" /> {{ t('新增') }}
        </a-button> -->
        <BasicTable class="mt-2" @register="registerAsnCTable" @row-click="handleAsnCRowClick" />

      </template>
    </BasicForm>
    <template #footer>
      <div v-if="record.canCommit">
        <BpmButton v-model:bpmEntity="record" bpmEntityKey="id" formKey="Flow_Srm_Asn_h" completeText="提交"
          :completeModal="true" :loading="loadingRef" :auth="'srm:asn:vouch:asnH:edit'" @validate="handleValidate"
          @complete="handleSubmit" @success="handleSuccess" @close="closeDrawer" />
      </div>
    </template>
  </BasicDrawer>
</template>
<script lang="ts" setup name="ViewsSrmAsnVouchAsnHForm">
  import { ref, unref, computed } from 'vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { Icon } from '/@/components/Icon';
  import { BasicForm, FormSchema, useForm } from '/@/components/Form';
  import { BasicTable, useTable } from '/@/components/Table';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { AsnH, asnHSave, asnHForm } from '/@/api/srm/asn/vouch/asnH';
  import { BpmButton } from '/@/components/Bpm';
  import { DictLabel } from '/@/components/Dict';

  const emit = defineEmits(['success', 'register']);

  const { t } = useI18n('srm.asn.vouch.asnH');
  const { showMessage } = useMessage();
  const { meta } = unref(router.currentRoute);
  const record = ref < AsnH > ({} as AsnH);
  const loadingRef = ref(false);

   let shStatus = ref('')

  const getTitle = computed(() => ({
    icon: meta.icon || 'i-ant-design:book-outlined',
    value: record.value.isNewRecord ? t('新增送货单') : t('编辑送货单'),
  }));

  const inputFormSchemas: FormSchema[] = [
    {
      label: t('基本信息'),
      field: 'info1',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('送货单号'),
      field: 'djno',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('公司'),
      field: 'company.companyName',
      component: 'Input',
      componentProps: {
        maxlength: 800,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('供应商'),
      field: 'basVen.cusname',
      component: 'Input',
      componentProps: {
        maxlength: 800,
        disabled: true,
      },
      required: true,
    },
    {
      label: t('公司主键'),
      field: 'pkCorp',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show:false
    },
    {
      label: t('供应商主键'),
      field: 'venId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show:false
    },
    {
      label: t('仓库主键'),
      field: 'wareId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show:false
    },
    {
      label: t('采购员主键'),
      field: 'cgId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show:false
    },
    {
      label: t('采购部门ID'),
      field: 'cgDeptId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show:false
    },
    {
      label: t('业务流程主键'),
      field: 'busType',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      // required: true,
      show:false
    },
     {
      label: t('收货人主键'),
      field: 'arrUserId',
      component: 'Input',
      componentProps: {
        maxlength: 64,
      },
      show:false
    },
    {
      label: t('仓库'),
      field: 'wareName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,
      },
      required: true,
    },
    
    {
      label: t('采购员'),
      field: 'cgName',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,

      },
      required: true,
    },
    {
      label: t('采购部门'),
      field: 'cgDeptName',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,

      },
      required: true,
    },
    
    {
      label: t('业务流程'),
      field: 'busTypeName',
      component: 'Input',
      componentProps: {
        maxlength: 100,
        disabled: true,

      },
      required: true,
    },

    // {
    //   label: t('单据状态'),
    //   field: 'djStatus',
    //   component: 'Select',
    //   componentProps: {
    //     disabled: true,
    //     dictType: 'xy_asn_dj_status'
    //   },
    // },
    {
      label: t('备注信息'),
      field: 'remarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        disabled:computed(() => shStatus.value != '5'&& shStatus.value != '6' && shStatus.value != '9')
      },
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('送货信息'),
      field: 'info2',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('预计到货'),
      field: 'planArrDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD',
        // showTime: { format: 'HH:mm' },
        disabled:computed(() => shStatus.value != '5'&& shStatus.value != '6' && shStatus.value != '9')
      },
      required: true,
    },


    {
      label: t('送货总数'),
      field: 'sumQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
        disabled: true,
      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },
    {
      label: t('收货总数'),
      field: 'sumArrQty',
      component: 'Input',
      componentProps: {
        maxlength: 16,
        disabled: true,

      },
      rules: [
        { pattern: /^(?:-?\d+|-?\d{1,3}(?:,\d{3})+)?(?:\.\d+)?$/, message: t('请输入一个数值') },
      ],
    },

    {
      label: t('收货人'),
      field: 'arrUserName',
      component: 'Input',
      componentProps: {
        maxlength: 50,
        disabled: true,

      },
    },
    {
      label: t('收货时间'),
      field: 'arrDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        showTime: { format: 'HH:mm' },
        disabled: true,
      },
    },
    {
      label: t('收货反馈'),
      field: 'arrRemarks',
      component: 'InputTextArea',
      componentProps: {
        maxlength: 500,
        disabled: true,
      },
      colProps: { lg: 24, md: 24 },
    },

    {
      label: t('制单信息'),
      field: 'info3',
      component: 'FormGroup',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t('制单人'),
      field: 'createByName',
      component: 'Input',
      componentProps: {
        maxlength: 400,
        disabled: true,

      },
    },
    {
      label: t('制单时间'),
      field: 'createDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        disabled: true,
        showTime: { format: 'HH:mm' },
      },
    },
    // {
    //   field: 'none',
    //   component: 'None',
    // },
    // {
    //   label: t('修改人'),
    //   field: 'updateByName',
    //   component: 'Input',
    //   componentProps: {
    //     maxlength: 400,
    //     disabled: true,

    //   },
    // },
    {
      label: t('修改时间'),
      field: 'updateDate',
      component: 'DatePicker',
      componentProps: {
        format: 'YYYY-MM-DD HH:mm',
        disabled: true,
        showTime: { format: 'HH:mm' },
      },
    },
    {
      field: 'none',
      component: 'None',
    },
    {
      label: '',
      field: 'detailInfo',
      component: 'Divider',
      colProps: { lg: 24, md: 24 },
    },
    {
      label: t(''),
      field: 'asnCList',
      component: 'Input',
      colProps: { lg: 24, md: 24 },
      slot: 'asnCList',
    },
  ];

  const [registerForm, { resetFields, setFieldsValue, updateSchema, validate }] = useForm({
    labelWidth: 120,
    schemas: inputFormSchemas,
    baseColProps: { lg: 8, md: 24 },
  });

  const [registerAsnCTable, asnCTable] = useTable({
    actionColumn: {
      ifShow:() => shStatus.value == '5' || shStatus.value == '6' || shStatus.value == '9' ,
      width: 60,
      actions: (record1: Recordable) => [
        {
          icon: 'i-ant-design:delete-outlined',
          color: 'error',
          popConfirm: {
            title: '是否确认删除',
            confirm: handleAsnCDelete.bind(this, record1),
          },
          auth: 'srm:asn:vouch:asnH:edit',
          // ifShow: () => record.djStatus == '0' || record.djStatus == '2',
          ifShow: () => shStatus.value == '5' || shStatus.value == '6' || shStatus.value == '9' ,
        },
      ],
    },
    rowKey: 'id',
    pagination: false,
    bordered: true,
    size: 'small',
    inset: true,
  });

  async function setAsnCTableData(_res: Recordable) {
    asnCTable.setColumns([
      // {
      //   title: t('公司主键'),
      //   dataIndex: 'pkCorp',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: true,
      // },
      {
        title: t('订单号'),
        dataIndex: 'orderCode',
        width: 130,
        align: 'left',
      },
      {
        title: t('订单行号'),
        dataIndex: 'crowno',
        width: 80,
        align: 'left',
      },
      // {
      //   title: t('存货ID'),
      //   dataIndex: 'invId',
      //   width: 130,
      //   align: 'left',
      //   editRow: true,
      //   editComponent: 'Input',
      //   editComponentProps: {
      //     maxlength: 64,
      //   },
      //   editRule: true,
      // },
      {
        title: t('存货编码'),
        dataIndex: 'basInv.cinvcode',
        width: 130,
        align: 'left',
      },
      {
        title: t('存货名称'),
        dataIndex: 'basInv.cinvname',
        width: 130,
        align: 'left',
      },
      {
        title: t('规格'),
        dataIndex: 'basInv.cinvspec',
        width: 130,
        align: 'left',
      },
      {
        title: t('型号'),
        dataIndex: 'basInv.cinvtype',
        width: 130,
        align: 'left',
      },
      {
        title: t('计量单位'),
        dataIndex: 'basInv.measname',
        width: 80,
        align: 'left',
      },
      {
        title: t('修改前数量'),
        dataIndex: 'hisQty',
        width: 100,
        align: 'left',
        ifShow:false
      },
      {
        title: t('送货数'),
        dataIndex: 'iqty',
        width: 100,
        align: 'center',
        // editRow: true,
        editRow: shStatus.value == '5' || shStatus.value == '6' || shStatus.value == '9'?true:false,
        editComponent: 'InputNumber',
        editComponentProps: {
          maxlength: 16,
          min:0
        },
        // editRule: true,
        editRule: shStatus.value == '5' || shStatus.value == '6' || shStatus.value == '9'?true:false,
      },
      {
        title: t('备注'),
        dataIndex: 'remarks',
        width: 150,
        align: 'left',
        // editRow: true,
        editRow: shStatus.value == '5' || shStatus.value == '6' || shStatus.value == '9'?true:false,
        editComponent: 'Input',
        editComponentProps: {
          maxlength: 100,
        },
      },
      {
        title: t('收货数量'),
        dataIndex: 'arrQty',
        width: 100,
        align: 'center',
        ifShow:record.value.djStatus == '2'?true:false
      },
      {
        title: t('收货反馈'),
        dataIndex: 'arrRemarks',
        width: 130,
        align: 'left',
        ifShow:record.value.djStatus == '2'?true:false
      },
    ]);
    asnCTable.setTableData(record.value.asnCList || []);
  }

  function handleAsnCRowClick(record: Recordable) {
    record.onEdit?.(true, false);
  }

  function handleAsnCAdd() {
    asnCTable.insertTableDataRecord({
      id: new Date().getTime(),
      isNewRecord: true,
      editable: true,
    });
  }

  function handleAsnCDelete(record: Recordable) {
    asnCTable.deleteTableDataRecord(record);
  }

  async function getAsnCList() {
    let asnCListValid = true;
    let asnCList: Recordable[] = [];
    for (const record of asnCTable.getDataSource()) {
      if (!(await record.onEdit?.(false, true))) {
        asnCListValid = false;
      }
      asnCList.push({
        ...record,
        id: !!record.isNewRecord ? '' : record.id,
      });
    }
    for (const record of asnCTable.getDelDataSource()) {
      if (!!record.isNewRecord) continue;
      asnCList.push({
        ...record,
        status: '1',
      });
    }
    if (!asnCListValid) {
      throw { errorFields: [{ name: ['asnCList'] }] };
    }
    return asnCList;
  }

  const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
    setDrawerProps({ loading: true });
    await resetFields();
    asnCTable.setTableData([]);
    const res = await asnHForm(data);
    record.value = (res.asnH || {}) as AsnH;
    record.value.__t = new Date().getTime();

    shStatus.value = record.value.status
    setFieldsValue(record.value);
    setAsnCTableData(res);
    // updateSchema([
    //   {
    //     field: 'djno',
    //     componentProps: {
    //       disabled: !record.value.isNewRecord,
    //     },
    //   },
    // ]);
    setDrawerProps({ loading: false });
  });

  async function handleValidate(_event: any, formData: any) {
    try {
      const data = await validate();
      formData(true, data); // 将表单数据传递给 BpmButton
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    }
  }

  async function handleSubmit(event: any) {
    try {
      loadingRef.value = true;
      // const data = event?.formData || (await validate()); // 接受 BpmButton 传递过来的表单数据
      const data = await validate(); // 接受 BpmButton 传递过来的表单数据
      data.bpm = Object.assign(data.bpm || {}, record.value.bpm); // 流程信息
      data.status = record.value.status; // 提交状态
      setDrawerProps({ confirmLoading: true });
      const params: any = {
        isNewRecord: record.value.isNewRecord,
        djno: record.value.djno,
      };
      if(shStatus.value != '5' && shStatus.value != '6' && shStatus.value != '9'){
        data.asnCList = record.value.asnCList
      }else{
        data.asnCList = await getAsnCList();
      }
      // console.log('submit', params, data, record);
      const res = await asnHSave(params, data);
      showMessage(res.message);
      setTimeout(closeDrawer);
      emit('success', data);
    } catch (error: any) {
      if (error && error.errorFields) {
        showMessage(t('common.validateError'));
      }
      console.log('error', error);
    } finally {
      loadingRef.value = false;
      setDrawerProps({ confirmLoading: false });
    }
  }

  async function handleSuccess() {
    emit('success');
  }
</script>